package com.jxt.myjxtmanager.ui.activity;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jxt.myjxtmanager.BaseActivity;
import com.jxt.myjxtmanager.R;
import com.jxt.myjxtmanager.db.Subject;
import com.jxt.myjxtmanager.ui.inter.SubjectInter;
import com.jxt.myjxtmanager.ui.presenter.SubjectPresenter;
import com.jxt.myjxtmanager.utils.LogUtils.LogInfo;
import com.jxt.myjxtmanager.utils.ScreenUtils;
import com.jxt.myjxtmanager.utils.ToastUtil;
import com.jxt.myjxtmanager.views.popwindow.Contect;
import com.jxt.myjxtmanager.views.popwindow.MyPopRecyOneToSixView;
import com.jxt.myjxtmanager.views.popwindow.PopRecyOneToSixInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * 成绩统计
 * Created by qm on 2017/3/7 0007.
 */
public class SubjectCountActivity extends BaseActivity implements OnChartValueSelectedListener, SubjectInter {

    PieChart mChart;
    private final String[] mSubject = new String[]{"数学", "语文", "英语", "科学", "美术", "体育", "实践课", "作文课", "阅读"};
    private final String[] mParties = new String[]{"优秀", "良好", "及格", "不及格"};
    private List<Integer> ints;

    private SubjectPresenter presenter;
    private Subject subjects;
    private MyPopRecyOneToSixView myPopRecyType;
    private MyPopRecyOneToSixView.OnItemClickListener onItemClickListener;
    private List<PopRecyOneToSixInfo>  infosType;
    private TextView tv_pop_isshow;
    private LinearLayout lin_triangle;
    private Button mTv_select_sn;

    @Override
    public void setMyAdapter() {
        presenter.dismissDialog();
        subjects = presenter.getQueryList(mSubject[0], 0);
        ints.add(Integer.parseInt(subjects.getSubScoreA()));
        ints.add(Integer.parseInt(subjects.getSubScoreB()));
        ints.add(Integer.parseInt(subjects.getSubScoreC()));
        ints.add(Integer.parseInt(subjects.getSubScoreD()));
        updatePieChart(mSubject[0]);
    }

    @Override
    public void updateRecycler() {

    }

    @Override
    public void showToastMsg(String msg) {
        if (!TextUtils.isEmpty(msg)) {
            ToastUtil.showToast(this, msg);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_score_count;
    }

    @Override
    protected void initView() {
        setToolbarTitle("成绩统计");
        setToolbarNavigationIcon(R.drawable.ic_left_return);
        mChart = (PieChart) findViewById(R.id.pieChart);
        lin_triangle = (LinearLayout) findViewById(R.id.lin_triangle);
        tv_pop_isshow = (TextView) findViewById(R.id.tv_pop_isshow);
        mTv_select_sn = (Button) findViewById(R.id.bt_select_subject);

        mTv_select_sn.setOnClickListener(this);
        ints = new ArrayList<>();
        presenter = new SubjectPresenter(this, this);
        presenter.RequestData();
        initPieChart(mSubject[0]);
        onItemClickListener = new MyPopRecyOneToSixView.OnItemClickListener() {
            @Override
            public void onItemClick(View view, String data, int position, boolean isLink) {
                subjects = presenter.getQueryList(mSubject[position], position);
                ints.clear();
                ints.add(Integer.parseInt(subjects.getSubScoreA()));
                ints.add(Integer.parseInt(subjects.getSubScoreB()));
                ints.add(Integer.parseInt(subjects.getSubScoreC()));
                ints.add(Integer.parseInt(subjects.getSubScoreD()));
                updatePieChart(mSubject[position]);
                mTv_select_sn.setText(data);
            }
        };

        Gson gson = new Gson();
        infosType = gson.fromJson(Contect.strType, new TypeToken<List<PopRecyOneToSixInfo>>() {
        }.getType());
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.bt_select_subject:
                //弹出popwindow
                ShowSelectPopWin(myPopRecyType, infosType);

                break;
        }
    }
    @Override
    public void onClickLeftMenu() {
        super.onClickLeftMenu();
    }

    private void updatePieChart(String name) {
        mChart.setCenterText(generateCenterSpannableText(name));
        setData(4, 100);
    }

    /**
         * 初始化饼状图
         * @param name
         */
        private void initPieChart(String name) {
            mChart.setUsePercentValues(true);
            mChart.getDescription().setEnabled(false);
            mChart.setExtraOffsets(5, 10, 5, 5);

            mChart.setDragDecelerationFrictionCoef(0.95f);

//        mChart.setCenterTextTypeface(mTfLight);
            mChart.setCenterText(generateCenterSpannableText(name));

            mChart.setDrawHoleEnabled(true);
            mChart.setHoleColor(Color.WHITE);

            mChart.setTransparentCircleColor(Color.WHITE);
            mChart.setTransparentCircleAlpha(110);

            mChart.setHoleRadius(58f);
            mChart.setTransparentCircleRadius(61f);

            mChart.setDrawCenterText(true);

            mChart.setRotationAngle(0);
            // enable rotation of the chart by touch
            mChart.setRotationEnabled(true);
            mChart.setHighlightPerTapEnabled(true);

            // mChart.setUnit(" €");
            // mChart.setDrawUnitsInChart(true);

            // add a selection listener
            mChart.setOnChartValueSelectedListener(this);

//        setData(4, 100);

            mChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
            // mChart.spin(2000, 0, 360);


            Legend l = mChart.getLegend();
            l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
            l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
            l.setOrientation(Legend.LegendOrientation.VERTICAL);
            l.setDrawInside(false);
            l.setXEntrySpace(7f);
            l.setYEntrySpace(0f);
            l.setYOffset(0f);

            // entry label styling
            mChart.setEntryLabelColor(Color.WHITE);
//        mChart.setEntryLabelTypeface(mTfRegular);
            mChart.setEntryLabelTextSize(12f);
        }

        /**
         * 设置饼状图数据
         * @param count
         * @param range
         */
    private void setData(int count, float range) {

        float mult = range;

        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();

        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
        for (int i = 0; i < count; i++) {
            entries.add(new PieEntry((float) (ints.get(i)),
                    mParties[i]));
        }

        PieDataSet dataSet = new PieDataSet(entries, "科目成绩统计");

//        dataSet.setDrawIcons(false);

        dataSet.setSliceSpace(3f);
//        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);

        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<Integer>();

        colors.add(ColorTemplate.getHoloBlue());
        for (int c : ColorTemplate.MATERIAL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
//        data.setValueTypeface(mTfLight);
        mChart.setData(data);

        // undo all highlights
        mChart.highlightValues(null);

        mChart.invalidate();
    }

    private SpannableString generateCenterSpannableText(String str) {//"MPAndroidChart\ndeveloped by Philipp Jahoda"
        int count = 0;
        for (int i = 0; i < ints.size(); i++) {
            count += ints.get(i);
        }
        String str1 = str + "\n" + "本班人数：" + count;
        SpannableString s = new SpannableString(str1);
        s.setSpan(new RelativeSizeSpan(1.7f), 0, str.length(), 0);
        s.setSpan(new StyleSpan(Typeface.NORMAL), str.length(), s.length() - str.length() - 1, 0);
        s.setSpan(new ForegroundColorSpan(Color.GRAY), str.length(), s.length() - str.length() - 1, 0);
        s.setSpan(new RelativeSizeSpan(.8f), str.length(), s.length() - str.length() - 1, 0);
        s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - str.length(), s.length(), 0);
        s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - str.length() - 1, s.length(), 0);
        return s;
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

        if (e == null)
            return;

        ToastUtil.showToast(this, "本班成绩" + mParties[(int) h.getX()] + ":" + (int) e.getY() + "人");
//        LogInfo.i("VAL SELECTED",
//                "Value: " + e.getY() + ", index: " + h.getX()
//                        + ", DataSet index: " + h.getDataSetIndex());
    }

    @Override
    public void onNothingSelected() {
        LogInfo.i("PieChart", "nothing selected");

    }


    /**
     * 弹出PopWindow  自定义  适合多种显示模式
     * @param myPopRecyOneToSixView
     * @param oneToSixInfos
     */
    private void ShowSelectPopWin(MyPopRecyOneToSixView myPopRecyOneToSixView, List<PopRecyOneToSixInfo> oneToSixInfos) {

        if (oneToSixInfos == null || oneToSixInfos.size() <= 0) {
            return;
        }
        if (myPopRecyOneToSixView == null) {
            myPopRecyOneToSixView = new MyPopRecyOneToSixView(SubjectCountActivity.this, SubjectCountActivity.this, SubjectCountActivity.this.getLayoutInflater(),
                    oneToSixInfos, ScreenUtils.getScreenW(SubjectCountActivity.this), onItemClickListener, false);
//            myPopRecyOneToSixView.showAsDropDown(mTv_select_sn);
        } else {
            myPopRecyOneToSixView.RefreshAdapterSelect();
//            myPopRecyOneToSixView.showAsDropDown(mTv_select_sn);
//                    myPopRecyView.dismiss();
//            backgroundAlpha(MyDevicesNoteActivity.this, 0.5f);//0.0-1.0
        }

        if (Build.VERSION.SDK_INT < 24) {//如果当前手机版本小于7.0  使用常规方法
            myPopRecyOneToSixView.showAsDropDown(mTv_select_sn, 0, 0);
        } else {// 否则则获取view的物理位置，设置popwindow的位置为物理位置
            int[] location = new int[2];
            // 获取控件在屏幕的位置
            mTv_select_sn.getLocationOnScreen(location);//获取View在屏幕中的物理位置
            myPopRecyOneToSixView.showAtLocation(mTv_select_sn, Gravity.NO_GRAVITY, 0, location[1] + mTv_select_sn.getHeight() + 0);
        }
        myPopRecyType = myPopRecyOneToSixView;
    }

}
